﻿const API_URL = 'http://localhost:8000/v1';


async function httpGetPlanets(){
    const response = await fetch(`${API_URL}/planets`);
    const planets = await response.json();
    console.log('planets', planets);
    return planets;
}

async function httpGetLaunches(){
    const response = await fetch(`${API_URL}/launches`);
    const launches = await response.json();
    console.log('launches', launches);
    return launches.sort((a,b) =>{
        return a.flightNumber - b.flightNumber;
    });
}

async function httpSubmitLaunch(launch){
    try{
        return await fetch(`${API_URL}/launches`, {
            method: 'POST',
            headers:{
                "Content-Type": "application/json",
            },
            body: JSON.stringify(launch),
        });
    }catch(err){
        return {
            ok: false,
        };
    }
}

async function httpAbortLaunch(flightNumber){
    try{
        return await fetch(`${API_URL}/launches/${flightNumber}`, {
            method: 'DELETE',
        });
    }catch(err){
        console.log(err);
        return {
            ok: false,
        }
    }
}

export {
    httpGetPlanets,
    httpGetLaunches,
    httpSubmitLaunch,
    httpAbortLaunch
}
